var hx = require("hbuilderx");
var fs = require('fs');

// var path = require("path");
// let root_path = path.resolve('./');


var status = 0;

//该方法将在插件激活的时候调用
function activate(context) {
	console.log('欢迎使用本插件，祝你身体健康，万事如意，开开心心发大财~');


	let disposable = hx.commands.registerCommand('extension.create', () => {

		if (status == 1) {
			hx.window.showInformationMessage('插件已激活，不要再点了')
			return false;
		}
		status = 1;

		let webviewPanel = hx.window.createWebView("GenerateWebView", {
			enableScritps: true
		});

		let webview = webviewPanel.webView;
		let background = '';
		let config = hx.workspace.getConfiguration();
		let colorScheme = config.get('editor.colorScheme');
		if (colorScheme == 'Monokai') {
			background = 'rgb(39,40,34)'
		} else if (colorScheme == 'Atom One Dark') {
			background = 'rgb(40,44,53)'
		} else {
			background = 'rgb(255,250,232)'
		};

			
		webview.html =
			`
		    <body style="background-color:${background};border:1px solid ${background};">
				<h1>请按下 CTRL + S 触发生成</h1>
		    </body>
		  `;

		// 消息监听
		webview.onDidReceiveMessage((msg) => {
			// 修改命令
			if(msg.command == 'edit'){
				let editorPromise = hx.window.getActiveTextEditor();
				editorPromise.then(function(editor) {
					let document = editor.document;
					editor.edit(editBuilder => {
						editBuilder.replace({
							start: 0, 
							end: document.getText().length
						}, msg.text);
					});
					
					// webview.postMessage({
					// 	command: a
					// });
				});
			}
			
			
			if (msg.command == 'alert') {
				hx.window.showInformationMessage(msg.text);
				// webview.postMessage({
				// 	command: a
				// });
			}
			
			
		});



		hx.window.showView({
			viewId: 'GenerateWebView',
			containerId: 'GenerateWebViewId'
		});






		// 文件保存的时候
		let onDidSaveTextDocumentEventDispose = hx.workspace.onDidSaveTextDocument(function(event) {
			// console.log(event);
			// 获取文件路径与行数
			console.log("当前触发保存的文件路径为: ", event.uri.fsPath);
			console.log("当前触发保存的文件行数为", event.lineCount);

			// console.log("当前触发保存的文件路径为: ", event.getText());

			var vue = event.getText();
			

			// var reg = /\<template[^>]*>(.|\n)*\<\/template\>/gims;
			// let template = reg.exec(str)
			
			// reg = /\<style[^>]*>(.|\n)*\<\/style\>/gims;
			// let style = reg.exec(str)
			
			// reg = /\<script[^>]*>(.|\n)*\<\/script\>/gims;
			// let script = reg.exec(str)
			
			// if (template == null) {
			// 	hx.window.showInformationMessage('未获取到<template></template\>')
			// }else{
			// 	template = template[0];
			// }
			
			// if (style != null) {
			// 	style = style[0];
			// }else{
			// 	style = ""
			// }
			
			// if (script != null) {
			// 	script = script[0];
			// }else{
			// 	script = ""
			// }


			webview.html =
				`
			    <body style="background-color:${background};border:1px solid ${background};">
					<div id="app">
						<div id="template">{{vue}}</div>
					</div>
					
					
					<button onclick="send();">点我传送</button>
					
			        <script src="https://lib.baomitu.com/vue/2.6.12/vue.min.js"></script>
			       <!-- <script src="http://hview.yzhaj.club/hview/hview.js"></script> -->
					
					<script >
						function init(){
							if('undefined' != typeof hbuilderx){
								console.log("初始化完成");
								hbuilderx.onDidReceiveMessage((msg) => {
									console.log(msg)
								});
							}else{
								setTimeout(()=>{
									init();
								},1000)
							}
						}
						init();
						
						
						function send() {
							hbuilderx.postMessage({
								command: 'edit',
								text: 'HelloWorld'
							});
						}
					
					
						var app = new Vue({
							el: '#app',
							data: {
								vue: \``+vue+`\`
							}
						})
					</script>
					
			    </body>
			    
			  `;


		});



	});






	//订阅销毁钩子，插件禁用的时候，自动注销该command。
	context.subscriptions.push(disposable);
}
//该方法将在插件禁用的时候调用（目前是在插件卸载的时候触发）
function deactivate() {
	console.log('该方法将在插件禁用的时候调用（目前是在插件卸载的时候触发')
}

module.exports = {
	activate,
	deactivate,
}
